import unittest
from public._snmp import snmpset
from random import randint
import time
from os import environ
from epics import caget,caput
import csv
from os import listdir,mkdir
environ["EPICS_CA_ADDR_LIST"] = "127.0.0.1:5064 10.10.14.198:5064"

file_path_node = "./WR-IMP-MIB-node.txt"
#_7100_pv = "Switch_10M:7100_1"
host_dict = {
    "TIMS:WR:TS_node03": "10.10.14.42",
    "TIMS:WR:TS_node04": "10.10.14.43"}


class file_opr():
    def __init__(self):
        if not "output" in listdir("."):
            mkdir("output")
        if not "BOS.csv" in listdir("./output"):
            with open("./output/BOS.csv","w",newline="",encoding="utf-8") as fp:
                fields = ["设备名","host","联锁次数","联锁输出次数","联锁输出成功率"]
                writer = csv.DictWriter(fp,fields)
                writer.writeheader()
                for name,host in host_dict.items():
                    writer.writerow({"设备名":name,"host":host,"联锁次数":0,"联锁输出次数":0,"联锁输出成功率":"100%"})
                writer.writerow({"设备名":"7100","host":"10.10.14.78","联锁次数":0,"联锁输出次数":0,"联锁输出成功率":"100%"})
                fp.close()
        
        with open("./output/BOS.csv".format(type),"r",newline="",encoding="utf-8") as fp:
            self.csv_bos_data = list(csv.reader(fp))
            fp.close()
    def write_data(self,host = None,flag=None):
        if host == "10.10.14.78":
            index = -1
        else:
            index = list(host_dict.values()).index(host)+1
        self.csv_bos_data[index][2] = int(self.csv_bos_data[index][2]) + 1
        if flag:
            self.csv_bos_data[index][3] = int(self.csv_bos_data[index][3]) + 1
        self.csv_bos_data[index][4] = "{:.2f}%".format(float(self.csv_bos_data[index][3])/float(self.csv_bos_data[index][2])*100)
        
            
    def write_csv(self):
        with open("./output/BOS.csv","w",newline="",encoding="utf-8") as fp:
            csv_write = csv.writer(fp)
            csv_write.writerows(self.csv_bos_data)
            fp.close()

class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        pass
        # cls.file_opr = file_opr()
    def loss_lock(self):
        _flag = False
        # random_index = set([randint(0,14) for i in range(randint(1,15))])
        random_index = range(randint(1,len(host_dict)))
        losslock_host = [list(host_dict.values())[i] for i in random_index]
        losslock_pv = [list(host_dict.keys())[i] for i in random_index]
        #_7100_flag = randint(0,1)
        # if _7100_flag == 1:
        #     print("本次联锁设备为：{} 以及 7100,联锁设备数量为:{}".format(" ".join(losslock_pv),len(random_index)+1))
        # else:
        print("本次联锁设备为：{},联锁设备数量为:{}".format(" ".join(losslock_pv),len(random_index)))
        # print(host_index)
        for host in losslock_host:
            a = snmpset(file_path=file_path_node,host=host,OIDname="impCtrlInterlockEna",set_type="i",set_value=1,mask="INTEGER:")
            a = snmpset(file_path=file_path_node,host=host,OIDname="impCtrlApply.0",set_type="i",set_value=11,mask="INTEGER:")
            # time.sleep(0.01)
        # if _7100_flag == 1:
        #     caput(_7100_pv,0)
        time.sleep(10)

        if caget("TIMS:WR:Enable_Bos") == 0:
            print("master 已联锁输出")
        else:

            print("master 联锁未输出")

        for host in losslock_host:
            #self.file_opr.write_data(host=host,flag=_flag)
            a = snmpset(file_path=file_path_node,host=host,OIDname="impCtrlInterlockEna",set_type="i",set_value=0,mask="INTEGER:")
            a = snmpset(file_path=file_path_node,host=host,OIDname="impCtrlApply.0",set_type="i",set_value=11,mask="INTEGER:")
        time.sleep(1)
        if caget("TIMS:WR:Enable_Bos") == 1:

            print("master 联锁恢复")
        else:
            print("master 联锁未恢复")
            # time.sleep(0.01)
        # if _7100_flag == 1:
        #     caput(_7100_pv,1)
        #     self.file_opr.write_data(host="10.10.14.78",flag=_flag)
        #self.file_opr.write_csv()
        

if __name__ == "__main__":
    for host in host_dict.values():
        a = snmpset(file_path=file_path_node,host=host,OIDname="impCtrlInterlockEna",set_type="i",set_value=0,mask="INTEGER:")
        a = snmpset(file_path=file_path_node,host=host,OIDname="impCtrlApply.0",set_type="i",set_value=11,mask="INTEGER:")
    num = 1
    while True:
        print("第{}次测试开始".format(num))
        suite = unittest.TestSuite()
        case_list = [Test("loss_lock")]
        # case_list = [Test("freqence")]
        suite.addTests(tests=case_list)
        runner = unittest.TextTestRunner()
        runner.run(suite)
        num += 1
        time.sleep(2)
    # while True:
    #     a = snmpset(file_path=file_path_node,host="10.10.14.41",OIDname="impCtrlInterlockEna",set_type="i",set_value=1,mask="INTEGER:")
    #     a = snmpset(file_path=file_path_node,host="10.10.14.41",OIDname="impCtrlApply.0",set_type="i",set_value=11,mask="INTEGER:")
    #     time.sleep(20)
    #     a = snmpset(file_path=file_path_node,host="10.10.14.41",OIDname="impCtrlInterlockEna",set_type="i",set_value=0,mask="INTEGER:")
    #     a = snmpset(file_path=file_path_node,host="10.10.14.41",OIDname="impCtrlApply.0",set_type="i",set_value=11,mask="INTEGER:")